<template>
  <div class="yoyo-container mx-auto min-h-screen pb-4 pb-[env(safe-area-inset-bottom)]">
    <!-- 导航栏 -->
    <navBar>
      <template #right>
        <img :src="cardSrc" class="w-5 h-5 " alt="" @click="goToCart" />
        <span class="text-sm mr-4">({{ cartItems.length }})</span>
        <img :src="mineSrc" class="w-5 h-5" alt="" @click="goToMine" />
      </template>
    </navBar>

    <!-- 搜索 -->
    <div
      class="w-4/5 mx-auto mt-2 bg-white min-h-12 rounded-full border border-gray-200 flex items-center justify-center pl-4"
      @click="showRegionPicker = true">
      <img :src="searchSrc" class="w-6 h-6" alt="" />
      <div class="w-full h-full pl-4 flex items-center justify-between pr-4" :placeholder="$t('home.searchText')">
        {{ selectedRegion }}
        <van-icon name="arrow-down" size="20" />
      </div>
    </div>
    <!-- 套餐和天数选择 -->
    <product-options :skus="detailInfo.packageList" ref="productOptions" />
    <!-- 产品描述 -->
    <product-describe :detailInfo="detailInfo" />
    <!-- 产品评价 -->
    <product-review :detailInfo="detailInfo" />
    <!-- 占位符 -->
    <div class="h-16"></div>

    <!-- 底部操作栏 -->
    <div class="fixed z-50 h-14 bottom-0 left-0 right-0 pb-[env(safe-area-inset-bottom)] yoyo-container mx-auto">
      <div class="flex items-center space-x-3 w-full lg:mx-4 lg:w-[calc(100%-2rem)] bg-white border-t border-gray-200 py-3 px-3">
        <!-- <van-icon name="like-o" size="24" class="text-gray-400" @click="handleFavorite" /> -->
        <van-icon
          :name="detailInfo.favorite ? 'like' : 'like-o'"
          :color="detailInfo.favorite ? '#ff7a00' : '#999'"
          size="24"
          @click.stop="handleFavorite(item)" />
        <van-icon name="chat-o" size="24" class="text-gray-400" />
        <div class="w-full flex items-center justify-end space-x-3">
          <van-button type="warning" round class="h-8 mr-2" color="#ff7a00" @click="addToCart">
            {{ $t("products.addToCart") }}
          </van-button>
          <van-button type="danger" round class="h-8" color="#ff7a00" @click="buyNow">{{ $t("products.buyNow") }}</van-button>
        </div>
      </div>
    </div>

    <!-- 地区选择弹窗 -->
    <van-popup v-model="showRegionPicker" position="bottom" round class="yoyo-container left-1/2 -translate-x-1/2 bg-transparent">
      <div class="p-3 lg:mx-4 lg:w-[calc(100%-2rem)] bg-white rounded-t-xl">
        <h3 class="text-lg font-medium mb-4 text-center">{{ $t("products.selectRegion") }}</h3>
        <div class="space-y-2 max-h-80 overflow-y-auto">
          <div
            v-for="region in regions"
            :key="region.code"
            class="flex items-center p-3 cursor-pointer hover:bg-gray-50 rounded"
            @click="selectRegion(region)">
            <img :src="imageBaseUrl + region.placeIcon" :alt="region.place" class="w-5 h-4 mr-3" />
            <span class="text-sm">{{ isZh ? region.place : region.placeEn }}</span>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import ProductOptions from "@/components/products/Options.vue"
import ProductDescribe from "@/components/products/Describe.vue"
import ProductReview from "@/components/products/Review.vue"
import { getProductDetail, getPlaceList } from "@/apis/shop"
import { addFavorite, removeFavorite } from "@/apis/favorite"
import { mapGetters } from "vuex"

export default {
  name: "ProductDetail",
  components: {
    "product-options": ProductOptions,
    "product-describe": ProductDescribe,
    "product-review": ProductReview,
  },
  data() {
    return {
      searchSrc: require("@/assets/images/search-icon.png"),
      cardSrc: require("@/assets/images/card-icon.png"),
      mineSrc: require("@/assets/images/mine-icon.png"),
      selectedRegion: "",
      showRegionPicker: false,
      regions: [],
      detailInfo: {},
      cartItems: [],
    }
  },
  computed: {
    ...mapGetters({
      isZh: "lang/isZh",
    }),
    imageBaseUrl() {
      return process.env.VUE_APP_IMAGE_URL
    },
    totalCount() {
      return this.cartItems.reduce((total, item) => total + item.quantity, 0)
    },
  },
  methods: {
    selectRegion(region) {
      this.selectedRegion = this.isZh ? region.place : region.placeEn
      this.showRegionPicker = false
      this.getProductDetail(region.id)
    },
    addToCart() {
      const cartItem = this.filterSettleData()

      // 从localStorage获取现有购物车数据
      let cartData = []
      const existingCart = localStorage.getItem("yoyotravel_cart")
      if (existingCart) {
        cartData = JSON.parse(existingCart)
      }

      // 检查是否已存在相同配置的商品
      const existingItemIndex = cartData.findIndex((item) => item.region === cartItem.region && item.selectedText === cartItem.selectedText)
      if (existingItemIndex > -1) {
        // 如果存在，增加数量
        cartData[existingItemIndex].quantity += cartItem.quantity
      } else {
        // 如果不存在，添加新商品
        cartData.push(cartItem)
      }

      // 保存到localStorage
      localStorage.setItem("yoyotravel_cart", JSON.stringify(cartData))
      // 显示成功提示
      this.$toast.success(this.$t("products.addedToCart"))
      console.log("加入购物车", cartItem)
    },
    buyNow() {
      const cartItem = this.filterSettleData()

      localStorage.setItem("yoyotravel_settleData", JSON.stringify([cartItem]))
      this.$router.push({ path: "/pay", query: { type: this.detailInfo.type } })
    },
    filterSettleData() {
      const { currentSecondLevel, currentFirstLevel, quantity, currentPrice, currentMarketPrice, getSelectedText } =
        this.$refs.productOptions
      const sku = currentSecondLevel ? currentSecondLevel.id : currentFirstLevel.id

      // 构建购物车商品数据
      const cartItem = {
        time: Date.now(), // 使用时间戳作为唯一ID
        sku: sku,
        region: this.detailInfo.type + " " + this.selectedRegion,
        selectedText: getSelectedText(),
        quantity: quantity,
        count: quantity,
        price: currentPrice,
        marketPrice: currentMarketPrice,
        type: this.detailInfo.type,
        picUrl: process.env.VUE_APP_IMAGE_URL + this.detailInfo.picUrl,
      }
      return cartItem
    },
    goToCart() {
      this.$router.push({ path: "/cart", query: { from: "detail" } })
    },
    goToMine() {
      this.$router.push({ path: "/mine" })
    },
    async getProductDetail(id) {
      try {
        const res = await getProductDetail({ id })
        this.detailInfo = res.data
      } catch (error) {
        console.log("object :>> ", error)
      }
    },
    async getPlaceList() {
      try {
        const { type, id } = this.$route.query
        console.log("id :>> ", id)
        const res = await getPlaceList({ type, keyword: "" })
        this.regions = res.data || []
        // console.log("this.regions :>> ", this.regions)
        const currentRegion = this.regions.find((item) => item.id == id)
        // console.log("currentRegion :>> ", currentRegion)
        console.log("this.isZh :>> ", this.isZh)
        this.selectedRegion = this.isZh ? currentRegion.place : currentRegion.placeEn
      } catch (error) {
        console.log("object :>> ", error)
      }
    },
    async handleFavorite() {
      try {
        if (this.detailInfo.favorite) {
          await removeFavorite({ spuId: this.detailInfo.id })
          this.detailInfo.favorite = false
        } else {
          await addFavorite({ spuId: this.detailInfo.id })
          this.detailInfo.favorite = true
        }
      } catch (error) {
        console.log("收藏操作失败 :>> ", error)
      }
    },

    loadCartData() {
      // 从localStorage加载购物车数据
      const cartData = localStorage.getItem("yoyotravel_cart")
      if (cartData) {
        this.cartItems = JSON.parse(cartData)
        console.log("this.cartItems :>> ", this.cartItems)
      }
    },
  },
  created() {
    this.getProductDetail(this.$route.query.id)
    this.getPlaceList()
    this.loadCartData()
  },
}
</script>

<style scoped>
.product-detail {
  /* padding-bottom: 80px; */
}

/* 自定义按钮样式 */
::v-deep .van-button--default {
  background-color: #f5f5f5;
  border-color: #e5e5e5;
  color: #666;
}

::v-deep .van-button--primary {
  background-color: #ff7a00;
  border-color: #ff7a00;
}

::v-deep .van-stepper {
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  overflow: hidden;
}
::v-deep .van-stepper {
  border: 0;
}
</style>
